﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Weixin.Core.config;

namespace Weixin.Core
{
    /// <summary>
    /// 微信辅助工具类
    /// </summary>
    public class WxAuxiliary
    {

        // 防止创建类的实例
        private WxAuxiliary() { }

        private static object locker = new object();

        private static int sn = 0;

        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <param name="startName"></param>
        /// <returns></returns>
        public static string GetOrderNumber(string startName)
        {
            lock (locker)
            {
                if (sn == 999999999)
                    sn = 0;
                else
                    sn++;
                return string.Format("{0}{1}{2}",startName,Next(1000,4), sn.ToString().PadLeft(2,'0'));
            }
        }

        /**
        * 生成随机串，随机串包含字母或数字
        * @return 随机串
        */
        public static string GenerateNonceStr()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }


        private static int Next(int numSeeds, int length)
        {

            byte[] buffer = new byte[length];

            System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();

            Gen.GetBytes(buffer);

            uint randomResult = 0x0;//这里用uint作为生成的随机数  
            for (int i = 0; i < length; i++)
            {
                randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
            }
            return (int)(randomResult % numSeeds);
        }

        /// <summary>
        /// 订单号防重复
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }


        /**
        * 根据当前系统时间加随机序列来生成订单号
        * @return 订单号
        */
        public static string GenerateOutTradeNo()
        {
            var ran = new Random();
            return string.Format("{0}{1}{2}", WxConfig.MchId,DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(999));
        }

    }
}
